import 'dart:async';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

///倒计时组件
class CountDownTimer extends StatefulWidget {
  ///小时
  final int hours;

  ///分钟
  final int minutes;

  ///秒数
  final int seconds;

  ///时间戳(将自动计算传入值与当前时间的差值，不能与时分秒同时传)
  final int timeStamp;

  ///文本样式
  final TextStyle? style;

  ///倒计时风格
  final CountDownStyle? countDownStyle;

  ///时间样式
  final TimeStyle timeStyle;

  ///小方框的背景颜色
  final Color? boxBackgroundColor;

  ///时间分隔符(冒号)的颜色
  final Color? colonColor;

  ///倒计时结束回调
  final VoidCallback? callback;

  ///倒计时组件
  CountDownTimer({
    super.key,
    this.hours = 0,
    this.minutes = 0,
    this.seconds = 0,
    this.timeStamp = 0,
    this.style,
    this.countDownStyle = CountDownStyle.pureText,
    this.timeStyle = TimeStyle.hhmmss,
    this.callback,
    this.boxBackgroundColor = Colors.white,
    this.colonColor = Colors.white,
  });

  @override
  _CountDownTimerState createState() => _CountDownTimerState();
}

class _CountDownTimerState extends State<CountDownTimer> {
  Timer? _timer;
  bool isOver = false;
  late num currentSecond;

  @override
  void initState() {
    super.initState();
    currentSecond = _getTotalSeconds();
    startCountDown();
  }
  
  @override
  void didUpdateWidget(covariant CountDownTimer oldWidget) {
    super.didUpdateWidget(oldWidget);
    currentSecond = _getTotalSeconds();
  }

  ///开始倒计时
  void startCountDown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (currentSecond >= 1) {
        setState(() {
          currentSecond -= 1;
        });
      } else {
        _timer?.cancel();
        if(widget.callback!=null){
          widget.callback!();
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return widget.countDownStyle == CountDownStyle.pureText
        ? _pureText()
        : _boxText();
  }

  ///计算待倒计时总秒数
  num _getTotalSeconds() {
    if (widget.timeStamp > 0) {
        var stamp = widget.timeStamp - DateTime.now().millisecondsSinceEpoch;
        if (stamp > 0) {
          return (stamp / 1000).floor();
        } else {
          return 0;
        }
      } else {
        return widget.hours * 3600 + widget.minutes * 60 + widget.seconds;
      }
  }
  ///获取剩余天数
  String _getDays(){
    var days = (currentSecond / (3600*24)).floor();
    return days.toString();
  }
  ///无天数时剩余小时数
  String _getHoursNoDays() {
    var hours = (currentSecond / 3600).floor();
    return "${hours > 9 ? hours : '0${hours}'}";
  }

  ///获取剩余小时数
  String _getHours() {
    var hours = (int.parse(_getHoursNoDays())%24).floor();
    return "${hours > 9 ? hours : '0${hours}'}";
  }

  ///获取剩余分钟数
  String _getMinutes() {
    var minutes = ((currentSecond % 3600) / 60).floor();
    return "${minutes > 9 ? minutes : '0${minutes}'}";
  }

  ///无小时时分钟数
  String _getMinutesNoHours() {
    var minutes = (currentSecond / 60).floor();
    return "${minutes > 9 ? minutes : '0${minutes}'}";
  }

  ///获取剩余秒数
  String _getSeconds() {
    var seconds = currentSecond % 60;
    return "${seconds > 9 ? seconds : '0${seconds}'}";
  }

  ///无小时和分时的秒数
  String _getSecondsNoHoursMinutes() {
    var seconds = currentSecond;
    return "${seconds > 9 ? seconds : '0${seconds}'}";
  }

  ///纯文本形式
  Widget _pureText() {
    switch (widget.timeStyle) {
      case TimeStyle.ddhhmmss:
      return Text(
          '${_getDays()}天${_getHours()}:${_getMinutes()}:${_getSeconds()}',
          style: widget.style,
        );
      case TimeStyle.hhmmss:
        return Text(
          '${_getHoursNoDays()}:${_getMinutes()}:${_getSeconds()}',
          style: widget.style,
        );
      case TimeStyle.mmss:
        return Text(
          '${_getMinutesNoHours()}:${_getSeconds()}',
          style: widget.style,
        );
      case TimeStyle.ss:
        return Text(
          '${_getSecondsNoHoursMinutes()}',
          style: widget.style,
        );
    }
  }

  ///小方框形式
  Widget _boxText() {
    switch (widget.timeStyle) {
      case TimeStyle.ddhhmmss:
      return Row(
          children: [
            _boxStyle(_getDays()),
            Container(
              margin: EdgeInsets.only(left: 4.w, right: 4.w),
              child: Text(
                '天',
                style: setTextStyle(10, FontWeight.bold, widget.colonColor!),
              ),
            ),
            _boxStyle(_getHours()),
            Container(
              margin: EdgeInsets.only(left: 4.w, right: 4.w),
              child: Text(
                ':',
                style: setTextStyle(10, FontWeight.bold, widget.colonColor!),
              ),
            ),
            _boxStyle(_getMinutes()),
            Container(
              margin: EdgeInsets.only(left: 4.w, right: 4.w),
              child: Text(
                ':',
                style: setTextStyle(10, FontWeight.bold, widget.colonColor!),
              ),
            ),
            _boxStyle(_getSeconds()),
          ],
        );
      case TimeStyle.hhmmss:
        return Row(
          children: [
            _boxStyle(_getHoursNoDays()),
            Container(
              margin: EdgeInsets.only(left: 4.w, right: 4.w),
              child: Text(
                ':',
                style: setTextStyle(10, FontWeight.bold, widget.colonColor!),
              ),
            ),
            _boxStyle(_getMinutes()),
            Container(
              margin: EdgeInsets.only(left: 4.w, right: 4.w),
              child: Text(
                ':',
                style: setTextStyle(10, FontWeight.bold, widget.colonColor!),
              ),
            ),
            _boxStyle(_getSeconds()),
          ],
        );
      case TimeStyle.mmss:
        return Row(
          children: [
            _boxStyle(_getMinutesNoHours()),
            Container(
              margin: EdgeInsets.only(left: 4.w, right: 4.w),
              child: Text(
                ':',
                style: setTextStyle(10, FontWeight.bold, Colors.white),
              ),
            ),
            _boxStyle(_getSeconds()),
          ],
        );
      case TimeStyle.ss:
        return Row(
          children: [
            _boxStyle(_getSecondsNoHoursMinutes()),
          ],
        );
    }
  }

  ///方框样式
  Widget _boxStyle(String text) {
    return Container(
      padding: EdgeInsets.only(left: 4.w, right: 4.w, top: 2.h, bottom: 2.h),
      decoration: BoxDecoration(
          color: widget.boxBackgroundColor,
          borderRadius: BorderRadius.all(Radius.circular(2.h))),
      child: Text(
        text,
        style: widget.style,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _timer!.cancel();
  }
}

///倒计时风格
enum CountDownStyle {
  ///纯文本
  pureText,

  ///小框框
  box
}

///时间样式
enum TimeStyle {
  ///天时分秒
  ddhhmmss,
  ///时分秒
  hhmmss,

  ///分秒
  mmss,

  ///秒
  ss
}
